package it.codelair.bakekaservice;

import it.codelair.bakekaservice.Utilities.NetworkCalls;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register_activity extends Activity implements OnClickListener{
	
	private String firstname;
	private String lastname;
	private String username;
	private String password;
	private String email;
	private View view;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		AccountManager accountMgr = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    	Account[] accounts = accountMgr.getAccountsByType("it.codelair.bakekaservice");
    	if(accounts!=null && accounts.length>0){
    		Intent home = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(home);
    	}
    	else{
			final Button registerButton= (Button) findViewById(R.id.registerAll);
			registerButton.setOnClickListener(this);
    	}
	}
	
	public void onClick(View v) {
		if(checkConn()){
			switch ( v.getId() ) {
			case R.id.registerAll:
				this.view = v;
				String error = controlFields();
				//registro l'account sul server e sul cell
				//autenticazione sul server
				if(error==null){
					if(checkConn()){
						new NetworkCalls(this).execute("http://www.bakekaservice.it/test/login/registerAndroid.php",this.firstname,this.lastname,this.username,this.password,this.email);
					}
					else {
            			Toast t = Toast.makeText(v.getContext(), "Connessione internet non disponibile!", Toast.LENGTH_SHORT);
            			t.show();
            		}
				}
				else {
					Toast t = Toast.makeText(v.getContext(), error, Toast.LENGTH_SHORT);
					t.show();
				}
				break;
			}
           
		}
		else {
			Toast t = Toast.makeText(v.getContext(), "Connessione internet non disponibile!", Toast.LENGTH_SHORT);
			t.show();
		}
	}
	
	public void createLocalAccount(String messageText) {
		if(messageText.equals("ok")){
			AccountManager man = (AccountManager) getSystemService(ACCOUNT_SERVICE);
			Account account = new Account(this.username, "it.codelair.bakekaservice");
			if (man.addAccountExplicitly(account, null, new Bundle())) {
				// account registrato: creazione tabella degli enti in sqlite e inizializzare il sincronizzatore
				
				
				//attivo il sincronizzatore
				 ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
				 ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
				 ContentResolver.addPeriodicSync(account, ContactsContract.AUTHORITY, new Bundle(),432000);
				
				
				Intent home = new Intent(getApplicationContext(), PrincipaleActivity.class);
	            startActivity(home);
	            this.finish();
			} else {
				Toast t = Toast.makeText(view.getContext(), "Problema nella registrazione dell'account", Toast.LENGTH_SHORT);
				t.show();
			}
		}
		else {
			Toast t = Toast.makeText(view.getContext(), messageText, Toast.LENGTH_SHORT);
			t.show();
		}
		
	}
	
	private String controlFields(){
		EditText firstNameText = (EditText) findViewById(R.id.editTextFirstName);
		EditText lastNameText = (EditText) findViewById(R.id.editTextLastName);
		EditText usernameText = (EditText) findViewById(R.id.editTextUsername);
		EditText emailText = (EditText) findViewById(R.id.editTextEmail);
		EditText passText = (EditText) findViewById(R.id.editTextPass);
		EditText pass2Text = (EditText) findViewById(R.id.editTextPass2);
		
		if(firstNameText==null || firstNameText.getText()==null || (""+firstNameText.getText()).equals("")
				|| lastNameText==null || lastNameText.getText()==null || (""+lastNameText.getText()).equals("")
				|| usernameText==null || usernameText.getText()==null || (""+usernameText.getText()).equals("")
				|| emailText==null || emailText.getText()==null || (""+emailText.getText()).equals("")
				|| passText==null || passText.getText()==null || (""+passText.getText()).equals("")
				|| pass2Text==null || pass2Text.getText()==null || (""+pass2Text.getText()).equals("")){
			return "Tutti i campi sono obbligatori";
		}
		this.email = ""+emailText.getText();
		if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
			return "Inserire una mail corretta";
		this.password = ""+passText.getText();
		if(!this.password.equals((""+pass2Text.getText())))
			return "Le password non corrispondono";
		this.firstname = ""+firstNameText.getText();
		this.lastname = ""+lastNameText.getText();
		this.username = ""+usernameText.getText();
		return null;
	}
	
	public boolean checkConn()
    {
        ConnectivityManager conMgr =  (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
        if (i == null)
          return false;
        if (!i.isConnected())
          return false;
        if (!i.isAvailable())
          return false;
        return true;
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register_activity, menu);
		return true;
	}

	public View getView() {
		return view;
	}

	public void setView(View view) {
		this.view = view;
	}


//	@Override
//	public void onResume(){
//		AccountManager accountMgr = (AccountManager) getSystemService(ACCOUNT_SERVICE);
//    	Account[] accounts = accountMgr.getAccountsByType("it.codelair.bakekaservice");
//    	if(accounts!=null && accounts.length>0){
//    		Intent home = new Intent(getApplicationContext(), Splash_activity.class);
//            startActivity(home);
//    	}
//    	else{
//    		super.onResume();
//    	}
//	}
}
